<template>
  <div class="tag-factory factory-calculate-config sql-config">
    <div class="factory-content" v-loading="loading">
      <el-row :gutter="20" class="sql-header">
        <el-col :span="6" align="left">
          <div class="factory-top">
            <icon-svg name="iconSql"></icon-svg>
            SQL创建工作台
          </div>
        </el-col>
        <el-col :span="18" align="right">
          <div class="btns">
            <el-button @click="handleReject">
              <icon-svg name="iconCancel"></icon-svg>
              清空
            </el-button>
            <el-button type="primary" @click="handlePreview">
              <icon-svg name="iconFacEye"></icon-svg>
              预览
            </el-button>
            <el-button type="primary" @click="handleSave">
              <icon-svg name="iconSave"></icon-svg>
              保存
            </el-button>
          </div>
        </el-col>
      </el-row>
      <div class="sql-content">
        <div class="sql-creator tag-scrollbar">
          <div class="creator-wrapper">
            <el-form :model="editForm" ref="editForm">
              <div
                v-for="(item, index) in editForm.configs"
                :key="index"
                class="config-item"
                :class="{ 'join-item': item.statementType === 2 }"
              >
                <div>
                  <el-row :gutter="20">
                    <el-col
                      :span="5"
                      align="right"
                      class="sql-type"
                      :class="{ 'select-item': item.statementType === 0 && item.isMulLine }"
                    >
                      <!-- <icon-svg :name="index === 0 ? 'iconSelect' : 'iconArrowTop'"></icon-svg><br /> -->
                      <span>{{ item.reveal }}</span>
                    </el-col>
                    <el-col :span="15">
                      <el-form-item
                        :prop="'configs.' + index + '.content'"
                        :rules="{
                          required: true,
                          message: '内容不能为空',
                          trigger: 'blur'
                        }"
                        v-if="item.statementType === 0"
                      >
                        <el-input
                          :placeholder="item.description"
                          v-model="item.content"
                          type="textarea"
                          :rows="5"
                          :show-word-limit="true"
                          resize="none"
                          v-if="item.isMulLine"
                        ></el-input>
                        <el-input :placeholder="item.description" v-model="item.content" v-else></el-input>
                      </el-form-item>
                      <template v-else-if="item.statementType === 1 || item.statementType === 2">
                        <el-row :gutter="20">
                          <el-col :span="17">
                            <el-form-item
                              :prop="'configs.' + index + '.content'"
                              :rules="{
                                required: true,
                                message: '内容不能为空',
                                trigger: 'change'
                              }"
                            >
                              <el-select
                                :placeholder="item.description"
                                v-model="item.content"
                                @change="changeTable($event, index)"
                              >
                                <el-option
                                  v-for="table in tableList"
                                  :key="table.tableNm"
                                  :label="table.tableNm"
                                  :value="table.tableNm"
                                ></el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span="7">
                            <el-form-item :prop="'configs.' + index + '.anotherName'">
                              <el-input placeholder="编辑表别名" v-model="item.anotherName"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </template>
                    </el-col>
                    <el-col :span="4">
                      <template v-if="item.columns !== 'ON'">
                        <el-dropdown trigger="click" v-if="index > 0">
                          <el-button type="primary" size="mini" icon="el-icon-plus" plain circle></el-button>
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-for="sql in sqlList" :key="sql.id" @click.native="addSql(sql, index)">
                              {{ sql.showSqlStatement }}
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown>
                        <el-button
                          type="warning"
                          size="mini"
                          icon="el-icon-minus"
                          plain
                          circle
                          v-if="index > 1"
                          @click="deleteSql(index)"
                        ></el-button>
                      </template>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-form>
          </div>
        </div>
        <div class="sql-result tag-scrollbar">
          <template v-if="previewResults.length">
            <div class="result-info">
              <img src="~@/assets/img/complete.png" /><br />
              运算成功！
            </div>
            <div class="story-box">
              <div class="story-title linear-blue">
                <span class="icon"><icon-svg name="iconCalculateResult"></icon-svg></span><br />
                结果预览
              </div>
              <div class="story-content ">
                <div class="result-title">
                  <el-row>
                    <el-col :span="4" align="center">
                      <span>序号</span>
                    </el-col>
                    <el-col :span="10" align="center">
                      <span>客户标识</span>
                    </el-col>
                    <el-col :span="10" align="center">
                      <span>标签值</span>
                    </el-col>
                  </el-row>
                </div>
                <ul class="result-content">
                  <li v-for="item in showResults" :key="item.order">
                    <el-row>
                      <el-col :span="4" align="center">
                        {{ item.order }}
                      </el-col>
                      <el-col :span="10" align="center">
                        {{ item.cust }}
                      </el-col>
                      <el-col :span="10" align="center">
                        {{ item.value }}
                      </el-col>
                    </el-row>
                  </li>
                </ul>
              </div>
            </div>
            <div class="express-info success" v-if="editForm.expression">
              执行SQL：
              <pre>{{ editForm.expression }}</pre>
            </div>
          </template>
          <template v-else-if="wrong">
            <div class="result-info wrong-info">
              <icon-svg name="iconWrong"></icon-svg><br />
              运算失败！
            </div>
            <div class="express-info">
              错误原因：
              <pre>{{ wrongInfo }}</pre>
            </div>
          </template>
          <div class="no-record" v-else>
            <img src="~@/assets/img/no_records.png" /><br />
            暂无内容
          </div>
        </div>
      </div>
    </div>
    <sql-drawer ref="sqlDrawer" @callback="confirm"></sql-drawer>
  </div>
</template>

<script>
import sqlDrawer from './sql-drawer'
export default {
  props: {
    logicalList: {
      type: Array,
      require: true,
      default: () => []
    }
  },
  components: { sqlDrawer },
  data() {
    return {
      loading: false,
      sqlList: [],
      tableList: [],
      editForm: {
        tagId: '',
        groupId: '',
        tagNm: '',
        tagStory: '',
        execFrequency: '',
        execTm: '',
        execWkList: [],
        execDtList: '',
        valueType: '',
        columnsNm: '',
        expression: '',
        rerun: false,
        rerunTime: 1,
        configs: [
          {
            reveal: 'SELECT',
            statementType: 0,
            columns: 'SELECT',
            description: '请输入字段名或其他',
            isMulLine: 1,
            content: '',
            tableName: '',
            dbName: '',
            anotherName: ''
          },
          {
            reveal: 'FROM',
            statementType: 1,
            columns: 'FROM',
            description: '请输入字段名或其他',
            isMulLine: 1,
            content: '',
            tableName: '',
            dbName: '',
            anotherName: ''
          }
        ]
      },
      previewResults: [],
      wrong: false,
      wrongInfo: ''
    }
  },
  created() {
    this.getSqlList()
    this.getTables()
  },
  computed: {
    showResults() {
      let result = []
      this.previewResults.forEach((item, index) => result.push({ order: index + 1, cust: item[0], value: item[1] }))
      return result
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$route.query.tagId) {
        this.editForm.tagId = this.$route.query.tagId
        this.getDetail()
      }
      this.editForm.groupId = this.$route.query.groupId
    })
  },
  methods: {
    getSqlList() {
      this.$ajax({
        url: this.$ajax.setUrl('der/derTagSqlCreate/getSqlStatement'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.sqlList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getTables() {
      this.$ajax({
        url: this.$ajax.setUrl('der/derTagSqlCreate/getSqlTableInfo'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.tableList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    addSql(item, index) {
      const params = {
        reveal: item.showSqlStatement,
        statementType: item.statementType,
        columns: item.sqlStatement,
        description: item.description,
        isMulLine: item.isMulLine,
        content: '',
        tableName: '',
        dbName: '',
        anotherName: ''
      }
      if (index === this.editForm.configs.length - 1) this.editForm.configs.push(params)
      else this.editForm.configs.splice(index + (this.editForm.configs[index].statementType === 2 ? 2 : 1), 0, params)
      if (item.statementType === 2) {
        // join等语句在后面加上on
        this.editForm.configs.splice(index + this.editForm.configs[index].statementType === 2 ? 3 : 2, 0, {
          reveal: 'ON',
          statementType: 0,
          columns: 'ON',
          description: '编辑表别名',
          isMulLine: 0,
          content: '',
          tableName: '',
          dbName: '',
          anotherName: ''
        })
        this.$forceUpdate()
      }
    },
    deleteSql(index) {
      const statementType = this.editForm.configs[index].statementType
      this.editForm.configs.splice(index, 1)
      if (statementType === 2) this.editForm.configs.splice(index, 1)
    },
    changeTable(tableName, index) {
      const tableTarget = this.tableList.find(item => item.tableNm === tableName)
      this.editForm.configs[index].dbName = tableTarget.dbName
      this.editForm.configs[index].tableName = tableTarget.tableNm
      if (index === 1) {
        // 修改
      }
      if (this.editForm.configs[index].statementType === 2) {
        // 修改join类,把后面的on内容改掉
        const leftTable = this.tableList.find(item => item.tableNm === this.editForm.configs[1].tableName)
        this.editForm.configs[index + 1].content = `${this.editForm.configs[1].tableName}.${
          leftTable.relaField
        } = ${tableName}.${tableTarget.relaField}`
      }
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`der/derTagSqlCreate/getSqlCreateInfo/${this.editForm.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editForm.tagNm = data.data.tagNm
          this.editForm.tagStory = data.data.tagStory
          this.editForm.valueType = data.data.valueType
          this.editForm.execFrequency = data.data.execFrequency
          this.editForm.execTm = data.data.execTm
          this.editForm.execWkList = data.data.execWkList
          this.editForm.execDtList = data.data.execDtList
          this.editForm.expression = data.data.expression
          this.editForm.columnsNm = data.data.columnsNm
          this.editForm.rerun = !!data.data.rerun
          this.editForm.rerunTime = data.data.rerunTime || 1
          this.editForm.configs = JSON.parse(data.data.tagConfigJson)
          this.previewResults = JSON.parse(data.data.previewResults)
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    handlePreview() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$ajax({
            url: this.$ajax.setUrl('der/derTagSqlCreate/showSqlCreate'),
            method: 'post',
            data: this.$ajax.setData({
              tagConfigJson: JSON.stringify(this.editForm.configs)
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.previewResults = data.data.previewResults
              this.editForm.expression = data.data.expression
              this.wrong = false
              this.wrongInfo = ''
              this.$message.success(data.msg)
            } else {
              this.previewResults = []
              this.editForm.expression = ''
              this.wrong = true
              this.wrongInfo = data.data
            }
            this.loading = false
          })
        }
      })
    },
    handleSave() {
      const params = {
        groupId: this.editForm.groupId,
        tagId: this.editForm.tagId,
        tagNm: this.editForm.tagNm,
        tagStory: this.editForm.tagStory,
        execFrequency: this.editForm.execFrequency,
        execTm: this.editForm.execTm,
        execWkList: this.editForm.execWkList,
        execDtList: this.editForm.execDtList,
        valueType: this.editForm.valueType,
        columnsNm: this.editForm.columnsNm,
        expression: this.editForm.expression,
        rerun: this.editForm.rerun,
        rerunTime: this.editForm.rerunTime,
        tagConfigJson: JSON.stringify(this.editForm.configs),
        previewResults: JSON.stringify(this.previewResults)
      }
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (!this.previewResults.length) {
            this.$message.info('请配置SQL语句并预览结果！')
            return
          }
          this.$refs.sqlDrawer.showDrawer(params)
        }
      })
    },
    confirm(params) {
      this.editForm.tagId = params.tagId
      this.editForm.tagNm = params.tagNm
      this.editForm.tagStory = params.tagStory
      this.editForm.valueType = params.valueType
      this.editForm.columnsNm = params.columnsNm
      this.editForm.rerun = params.rerun
      this.editForm.rerunTime = params.rerunTime
      this.editForm.execFrequency = params.execFrequency
      this.editForm.execTm = params.execTm
      this.editForm.execWkList = params.execWkList
      this.editForm.execDtList = params.execDtList
    },
    handleReject() {
      this.$confirm('确定清空所有语句？').then(() => {
        this.editForm.configs = [
          {
            reveal: 'SELECT',
            statementType: 0,
            columns: 'SELECT',
            description: '请输入字段名或其他',
            isMulLine: 1,
            content: '',
            tableName: '',
            dbName: '',
            anotherName: ''
          },
          {
            reveal: 'FROM',
            statementType: 1,
            columns: 'FROM',
            description: '请输入字段名或其他',
            isMulLine: 1,
            content: '',
            tableName: '',
            dbName: '',
            anotherName: ''
          }
        ]
        this.previewResults = []
      })
    }
  }
}
</script>

<style lang="scss">
@import '../../factory/factory.scss';
.sql-config {
  .factory-content {
    margin-left: 10px !important;
  }
  .sql-header {
    box-shadow: 1px 1px 3px #ddd;
  }
  .sql-content {
    height: calc(100% - 60px);
    display: flex;
    .sql-creator {
      width: 40%;
      height: 100%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      border-right: 1px solid #ddd;
      .creator-wrapper {
        padding: 20px 30px;
        position: relative;
        &:before {
          width: 3px;
          background-color: $theme-color;
          content: '';
          position: absolute;
          top: 20px;
          bottom: 20px;
          left: 0;
        }
      }
      .config-item:not(:last-of-type) {
        margin-bottom: 20px;
        &.join-item {
          margin-bottom: 0;
          .sql-type:after {
            bottom: -10px;
          }
          & + .config-item {
            .sql-type:after {
              top: -15px;
            }
          }
        }
      }
      .sql-type {
        font-size: 20px;
        padding: 5px 0;
        margin-top: 10px;
        color: $theme-color;
        position: relative;
        span {
          margin-right: 15px;
        }
        svg {
          width: 40px;
          height: 40px;
          color: #1296db;
          margin-bottom: 5px;
        }
        &:after {
          width: 3px;
          background-color: #1296db;
          content: '';
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
        }
      }
      .select-item {
        height: 120px;
        line-height: 120px;
        margin-top: 0;
      }
      .el-form-item {
        margin-bottom: 0;
      }
      .el-select {
        width: 100%;
      }
      .el-input {
        margin-top: 5px;
        padding: 0;
      }
      .el-input__suffix {
        top: -2px;
      }
      .el-form-item__error {
        top: auto;
        bottom: -5px;
      }
      .el-button {
        margin: 5px 10px 0 0;
      }
      .el-dropdown {
        margin-top: 10px;
      }
    }
  }
  .sql-result {
    flex: 1;
    padding: 0 20px;
    overflow-y: auto;
  }
  .result-info {
    font-size: 16px;
    font-weight: bold;
    padding: 50px;
    margin: 20px 0;
    text-align: center;
    color: #666;
    background-color: #f6fbf8;
    img {
      margin-bottom: 20px;
    }
    svg {
      width: 88px;
      height: 88px;
      margin-bottom: 20px;
    }
  }
  .wrong-info {
    color: $tag-red;
  }
  .express-info {
    padding: 20px;
    color: $theme-color;
    font-weight: bold;
    background-color: #f6fbf8;
    pre {
      font-size: 17px;
      color: $tag-red;
      line-height: 30px;
      padding: 0 30px;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
    &.success {
      margin-top: 20px;
      pre {
        color: $tag-green;
      }
    }
  }
  .story-box {
    margin-top: 20px;
    height: 310px;
    border-radius: 5px;
    box-shadow: 1px 1px 3px #ddd, -1px -1px 3px #ddd;
    overflow: hidden;
    position: relative;
  }
  .story-title {
    font-size: 17px;
    font-weight: bold;
    width: 200px;
    height: 100%;
    color: #fff;
    text-align: center;
    position: relative;
    &:before {
      width: 100%;
      height: 100%;
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      background: url(~@/assets/img/params_bg.png) no-repeat 0px 0px/100% 100%;
    }
  }
  .icon {
    display: inline-block;
    width: 80px;
    height: 80px;
    background-color: #fff;
    margin: 80px 0 10px;
    border-radius: 50%;
    svg {
      width: 50px;
      height: 50px;
      margin-top: 15px;
    }
  }
  .linear-blue {
    background: linear-gradient(to bottom, #63a3fc, #5188ec);
    svg {
      color: #5188ec;
    }
  }
  .story-content {
    padding-left: 200px;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  }
  .story-text {
    padding: 13px 15px 13px 215px;
    .el-textarea.is-disabled .el-textarea__inner {
      color: #666;
      cursor: default;
    }
  }
  .result-title {
    font-weight: bold;
    height: 60px;
    border-bottom: 1px solid #eee;
    span {
      display: inline-block;
      width: 80%;
      height: 40px;
      line-height: 40px;
      margin: 10px 0 10px 0;
      background-color: #fcf5e5;
      border-radius: 20px;
    }
  }
  .result-content {
    height: calc(100% - 60px);
    overflow-y: auto;
    li {
      height: 40px;
      line-height: 40px;
    }
  }
  .no-record {
    margin: 20px 0;
    text-align: center;
    img {
      margin-bottom: 10px;
    }
  }
}
</style>
